package com.example.common.utils;

import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;

public class RedisIdWorkUtil {
    //开始时间戳 2025-01-01 00:00:00
    private static final long START_TIMESTAMP = 1735689600L;
    private final StringRedisTemplate stringRedisTemplate;

    public RedisIdWorkUtil(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }

    public long nextId(String keyPrefix) {
        //生成时间戳
        LocalDateTime now = LocalDateTime.now();
        long nowSecond = now.toEpochSecond(ZoneOffset.UTC);
        long timestamp = nowSecond - START_TIMESTAMP;
        //生成序列号
        // 获取当前日期, 精确到天
        String date = now.format(DateTimeFormatter.ofPattern("yyyy:MM:dd"));
        long count = stringRedisTemplate.opsForValue().increment("icr:"+keyPrefix +":"+ date);
        //拼接并返回
        return timestamp << 32 | count;
    }
}
